package com.maple.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.maple.dto.UserLoginDTO;
import com.maple.entity.User;
import com.maple.enumeration.ExceptionEnum;
import com.maple.exception.BusinessException;
import com.maple.mapper.UserMapper;
import com.maple.service.UserService;
import com.maple.utils.AlipayUtils;
import com.maple.utils.ThreadLocalUtils;
import com.maple.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    /**
     * 用户登陆
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        // 判断授权码是否存在
        if(userLoginDTO.getCode() == null){
            throw new BusinessException(ExceptionEnum.LOGIN_FAILED);
        }

//        使用支付宝接口获得令牌信息、用户openid和其他数据
        AlipaySystemOauthTokenResponse request;
        AlipayUserInfoShareResponse userInformation;
        try {
            request = AlipayUtils.getRequest(userLoginDTO.getCode());
            userInformation = AlipayUtils.getUserInformation(request.getAccessToken());
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

//      查询是否是新用户
        User user = userMapper.queryByOpenId(userInformation.getUserId());
        if(user != null){
            return user;
        }

//          数据库新增用户对象
        user = User.builder()
                .sex(userInformation.getGender())
                .name(userInformation.getNickName())
                .phone(userInformation.getPhone())
                .avatar(userInformation.getAvatar())
                .openid(userInformation.getUserId())
                .createTime(LocalDateTime.now())
                .build();
        userMapper.save(user);

//        返回值
        return user;

    }
















}
